define(['jquery', 'bootstrap', 'backend', 'table', 'form'], function ($, undefined, Backend, Table, Form) {

    var Controller = {
        index: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'identity_info/index' + location.search,
                    add_url: 'identity_info/add',
                    edit_url: 'identity_info/edit' + location.search,
                    del_url: 'identity_info/del',
                    multi_url: 'identity_info/multi',
                    import_url: 'identity_info/import',
                    table: 'identity_info',
                }
            });

            var table = $("#table");

            // 获取区域列表数据，转换为searchList格式
            var areaList = typeof Config !== 'undefined' && Config.areaList ? Config.areaList : {};
            var areaSearchList = {};
            for (var areaId in areaList) {
                if (areaList.hasOwnProperty(areaId)) {
                    areaSearchList[areaId] = areaList[areaId];
                }
            }
            
            // 获取学历列表数据，转换为searchList格式
            var educationList = typeof Config !== 'undefined' && Config.educationList ? Config.educationList : {};
            var educationSearchList = {};
            for (var education in educationList) {
                if (educationList.hasOwnProperty(education)) {
                    educationSearchList[education] = educationList[education];
                }
            }

            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'id',
                fixedColumns: true,
                search:false,
                fixedRightNumber: 1,
                columns: [
                    [
                        {checkbox: true},
                        {field: 'id', title: __('Id')},
                        {
                            field: 'user.nickname',
                            title: __('User'),
                            operate: 'LIKE',
                            halign: "center",
                            searchable: false,
                            formatter: Table.api.formatter.content
                        },
                        // {field: 'school', title: __('School'), operate: 'LIKE', table: table, class: 'autocontent', formatter: Table.api.formatter.content},
                        {field: 'name', title: __('Name'), operate: false, table: table, class: 'autocontent', formatter: Table.api.formatter.content},
                        {field: 'identity_info.name', title: __('Name'), operate: 'LIKE',visible: false, table: table, class: 'autocontent', formatter: Table.api.formatter.content},
                        {field: 'phone', title: __('Phone'), operate: 'LIKE'},
                        {field: 'age', title: __('Age'), operate: 'BETWEEN'},
                        {field: 'education_background', title: __('Education_background'), operate: '=', searchList: educationSearchList},
                        {field: 'area', title: __('地区'), operate: 'FIND_IN_SET', searchList: areaSearchList, formatter: function(value, row, index) {
                            return row.area_name || '';
                        }},
                        // {field: 'is_all', title: __('Is_all'), operate: 'LIKE', table: table, class: 'autocontent', formatter: Table.api.formatter.content},
                        // {field: 'hourly_rate', title: __('Hourly_rate'), operate:'BETWEEN'},
                        {field: 'appointment_time_week', title: __('Appointment_time_week'), operate: 'LIKE', table: table, class: 'autocontent', formatter: Table.api.formatter.content},
                        {field: 'appointment_time', title: __('Appointment_time'), operate: false, table: table, class: 'autocontent', formatter: Table.api.formatter.content},
                        // {field: 'is_premium', title: __('是否精品'), formatter: Table.api.formatter.toggle, searchList: {0: __('否'), 1: __('是')}},
                        {field: 'main_score', title: __('Main_score'), operate: 'LIKE', table: table, class: 'autocontent', formatter: Table.api.formatter.content},
                        // {field: 'user_score', title: __('User_score'), operate: 'LIKE', table: table, class: 'autocontent', formatter: Table.api.formatter.content},
                        {field: 'main_people', title: __('People'), operate: 'LIKE', table: table, class: 'autocontent', formatter: Table.api.formatter.content},
                        {field: 'main_status', title: __('展示'), formatter: Table.api.formatter.toggle, searchList: {2: __('否'), 1: __('是')}},
                        {field: 'addtime', title: __('Addtime'), operate:false, addclass:'datetimerange', autocomplete:false},
                        {field: 'identity_info.addtime', title: __('Addtime'), operate:'RANGE', addclass:'datetimerange', autocomplete:false,visible: false},
                        {
                            field: 'operate',
                            title: __('Operate'),
                            table: table,
                            events: Table.api.events.operate,
                            formatter: Table.api.formatter.operate,
                            buttons: [
                                {
                                    name: 'club_dtl',
                                    text: '课程',
                                    title: function (row) {
                                        return `${row.name}  课程 列表`;
                                    },
                                    classname: 'btn btn-xs btn-info btn-dialog',
                                    icon: 'fa fa-align-justify',
                                    extend: 'data-area=\'["90%", "80%"]\'',
                                    url: function (row) {
                                        return `teacher_detail?info_id=${row.id}`;
                                    },
                                    callback: function (data) {
                                        $(".btn-refresh").trigger("click"); //刷新数据
                                    }
                                }
                            ]
                        }
                    ]
                ]
            });

            $("#club_two_id").data("params", function () {
                return {custom: {club_id: $("#club_one_id").val()}};
            });

            // 为表格绑定事件
            Table.api.bindevent(table);
        },
        add: function () {
            Controller.api.bindevent();
        },
        edit: function () {
            Controller.api.bindevent();
        },
        api: {
            bindevent: function () {
                Form.api.bindevent($("form[role=form]"));
                $("#c-club_two_id").data("params", function () {
                    return {custom: {club_id: $("#c-club_one_id").val()}};
                });
                
                // 监听 Club_one 的变化
                $("#c-club_one_id").on('change', function() {
                    $("#c-club_two_id").selectPageClear();
                });

                // 监听生日变化，自动计算年龄
                $("#c-birthday").on('change dp.change', function(){
                    var birthday = $(this).val();
                    if (birthday) {
                        var age = calculateAge(birthday);
                        $("#c-age").val(age);
                    } else {
                        // 如果生日为空，清空年龄
                        $("#c-age").val('');
                    }
                });

                // 监听日期选择器的隐藏事件
                $("#c-birthday").on('dp.hide', function(){
                    var birthday = $(this).val();
                    if (birthday) {
                        var age = calculateAge(birthday);
                        $("#c-age").val(age);
                    } else {
                        $("#c-age").val('');
                    }
                });

                // 监听输入框的输入事件
                $("#c-birthday").on('input blur', function(){
                    var birthday = $(this).val();
                    if (birthday) {
                        var age = calculateAge(birthday);
                        $("#c-age").val(age);
                    } else {
                        $("#c-age").val('');
                    }
                });

                // 页面加载时初始化年龄计算（用于编辑页面）
                $(document).ready(function(){
                    var birthday = $("#c-birthday").val();
                    if (birthday) {
                        var age = calculateAge(birthday);
                        $("#c-age").val(age);
                    }
                });

                // 计算年龄的函数
                function calculateAge(birthday) {
                    var today = new Date();
                    var birthDate = new Date(birthday);
                    var age = today.getFullYear() - birthDate.getFullYear();
                    var monthDiff = today.getMonth() - birthDate.getMonth();
                    
                    if (monthDiff < 0 || (monthDiff === 0 && today.getDate() < birthDate.getDate())) {
                        age--;
                    }
                    
                    return age;
                }

                // 监听时间变化，更新隐藏字段
                // $('#c-start_time, #c-end_time').on('change', function(){
                //     var startTime = $('#c-start_time').val();
                //     var endTime = $('#c-end_time').val();
                //     $('#c-appointment_time').val(startTime + ' - ' + endTime);
                // });
            }
        }
    };
    return Controller;
});
